#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <string>
int cnt = 3;
std::string testList[3] = {"test", "test2", "test3"};
int main()
{
    // execl("/bin/ls", "ls", "-l", NULL);
    // execl("test3", NULL);
    // 创建3个子进程分别执行test test2 test3
    char* argv[] = {(char*)"ls", (char*)"-l"};
    for(int i = 0; i < cnt; ++i)
    {
        pid_t pid = fork();
        if(pid == 0)
        {
            // 子进程
            std::cout << "Child process running with PID: " << getpid() << std::endl;
            sleep(2); // Simulate some work in the child process
            std::cout << "Executing: " << i << std::endl;
            //execl(testList[i].c_str(), testList[i].c_str(), NULL);
            //execlp("ls", "ls", "-l", NULL);
            //execv("/usr/bin/ls", argv);
            execvp("ls", argv);
            std::cout << "Child process exiting." << std::endl;
            return 0;
        }
        else if(pid < 0)
        {
            // Fork failed
            perror("fork");
            return 1;
        }
    }
    // 父进程等待子进程
    int status;
    pid_t result;
    do
    {
        result = waitpid(-1, &status, WNOHANG);
        if(result == 0)
        {
            std::cout << "Parent process waiting for child process (non-blocking)." << std::endl;
            sleep(1);
        }
        else if(result == -1)
        {
            std::cout << "Error: " << strerror(errno) << std::endl;
            break;
        }
        else
        {
            std::cout << "Child process terminated with PID: " << result << std::endl;
            if(WIFEXITED(status))
            {
                std::cout << "Child exited with status: " << WEXITSTATUS(status) << std::endl;
            }
            else
            {
                std::cout << "Child did not exit normally." << std::endl;
            }
        }
    } while(result > 0);
    
    return 0;
}